/*
 * @Author: duanguang
 * @Date: 2021-12-18 21:54:52
 * @LastEditTime: 2021-12-19 13:41:34
 * @LastEditors: duanguang
 * @Description: 
 * @FilePath: /legions-server/app/io/controller/initProject.ts
 * 「扫去窗上的尘埃，才可以看到窗外的美景。」
 */
import { SocketRespone } from '@/utils/socketResponse';
import { Controller } from 'egg';
const uuidv1 = require('uuid/v1');
import { SimpleGit } from 'simple-git';
import simpleGit from 'simple-git/promise';
import * as shell from 'shelljs';
const project_workspace = `${process.cwd()}/app/git-repository`
interface IIintProjectRequest{
  project_name: string;
  source_git_url: string;
  modules_name: string;
  component_name?: string;
  template_type?: string;
  source_branch:string
}
export default class InitProjectController extends Controller {
  public async index() {
    if (this.ctx.args && Array.isArray(this.ctx.args) && this.ctx.args[0]) {
      const params = this.ctx.args[0] as IIintProjectRequest
      const uid = uuidv1()
      let responeModel = new SocketRespone<IIintProjectRequest,{ uid: string; message: string }>(params,{
        uid,
        message:`正在拉取仓库信息:${project_workspace}/${uid}`
      },'pending')
      shell.mkdir('-p',`${project_workspace}/${uid}`)
      this.ctx.socket.emit('message',responeModel)
      let git: SimpleGit | null = await simpleGit(`${project_workspace}/${uid}`);
      const result = await git.clone(params.source_git_url);
      responeModel.response.message=result
      this.ctx.socket.emit('message',responeModel)
      git = null;
      const source_branch = params.source_branch.replace('origin/','')
      git = await simpleGit(`${project_workspace}/${uid}/${params.project_name}`);
      console.log(source_branch,'source_branch')
      const resultCheckout = await git.checkout(['-b',source_branch,params.source_branch])
      responeModel.state = 'complete'
      responeModel.response.message = resultCheckout
      this.ctx.socket.emit('message',responeModel)
    }
  }
}
